package org.openea.eap.module.obpm.controller.form;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.rest.ControllerTools;
import org.openbpm.base.rest.util.RequestUtil;
import org.openea.eap.module.obpm.service.form.FormImExportService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping({"/form/imExport/"})
public class FormImExportController extends ControllerTools {

    @Resource
    private FormImExportService formImExportService;

    @RequestMapping({"export"})
    @CatchErr("exportForm异常")
    public void exportFormXml(HttpServletRequest request, HttpServletResponse response, String ids) throws Exception {
        // 导出文件用zip压缩
        // fromXmlList -> formXml -> html + businessObject
        // businessObject (relationJson + busTable(busColumn(ctrJson) ) )
        String[] objIds = RequestUtil.getStringAryByStr(request, "ids");
        if (ArrayUtil.isEmpty(objIds)) {
            return;
        }
        String zipName = "form" + DateUtil.format(new Date(), "yyyy_MMdd_HHmm");
        Map<String, String> exportXml = this.formImExportService.exportFormXmlList(objIds);
        downLoadXmlZipFile(request, response, exportXml, zipName);
    }

    @RequestMapping({"importOverView"})
    @CatchErr("importOverView异常")
    public ResultMsg<List<Map<String, Object>>> importFormOverView(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String formXml = getXmlFromZipFile(request, "form.xml");
            List<Map<String, Object>> previewList = this.formImExportService.importFormPreview(formXml);
            return getSuccessResult(previewList);
        } catch (Exception e) {
            throw e;
            //throw new RuntimeException(e);
        }
    }


    @RequestMapping({"importSave"})
    @CatchErr("importSave异常")
    public ResultMsg<String> importFormSave(@RequestBody List<JSONObject> overViewList) throws Exception {
        // 输入参数overViewList为importFormOverView的输出数据
        if (CollectionUtil.isEmpty(overViewList)) {
            throw new RuntimeException("导入的数据不能为空！");
        }
        this.formImExportService.importFormSave(overViewList);
        return getSuccessResult("导入成功!");
    }
}
